<?php

/*
////////////////////////////////////////////////////////////////////////////////
// JohnCMS                             Content Management System              //
// Официальный сайт сайт проекта:      http://johncms.com                     //
// Дополнительный сайт поддержки:      http://gazenwagen.com                  //
////////////////////////////////////////////////////////////////////////////////
// JohnCMS core team:                                                         //
// Евгений Рябинин aka john77          john77@gazenwagen.com                  //
// Олег Касьянов aka AlkatraZ          alkatraz@gazenwagen.com                //
//                                                                            //
// Информацию о версиях смотрите в прилагаемом файле version.txt              //
////////////////////////////////////////////////////////////////////////////////
*/

defined('_IN_JOHNCMS') or die('Restricted access');

class mainpage extends core {
    public $news;    // Текст новостей
    public $newscount;    // Общее к-во новостей
    public $lastnewsdate;    // Дата последней новости
    private $settings = array();

    function __construct() {
        $this->settings = unserialize(self::$system_set['news']);
        $this->newscount = $this->newscount() . $this->lastnewscount();
        $this->news = $this->news();
    }

    // Запрос свежих новостей на Главную
    private function news() {
        if ($this->settings['view'] > 0) {
            $reqtime = $this->settings['days'] ? time() - ($this->settings['days'] * 86400) : 0;
			
            $req = mysql_query("SELECT `cms_news`.*, `cms_news_cat`.`name` as `catname`, `cms_news_cat`.`id` as `catid` FROM `cms_news` LEFT JOIN `cms_news_cat` ON `cms_news`.`refid`=`cms_news_cat`.`id` WHERE `cms_news`.`time` > '$reqtime'".(self::$user_rights < 7 ? " AND `cms_news`.`time`<='" . time() . "'":"")." ORDER BY `cms_news`.`time` DESC LIMIT " . $this->settings['quantity']);
            if (mysql_num_rows($req) > 0) {
                //$news = '<div class="phdr"><b>' . self::$lng['news'] . '</b></div>';
                $news = '';
				while ($res = mysql_fetch_array($req)) {
                    $text = $res['text'];
                    // Если текст больше заданного предела, обрезаем
                    if(mb_strlen($text) > $this->settings['size']) {
						$str = mb_substr($text, 0, $this->settings['size']);
						$text = htmlentities(mb_substr($str, 0, mb_strrpos($str, ' ')), ENT_QUOTES, 'UTF-8') . ' <br></br><a href="news/index.php?act=view&amp;id=' . $res['id'] . '">...далее</a>';
					} else {
						$text = htmlentities($text, ENT_QUOTES, 'UTF-8');
					}
                    // Если включены переносы, то обрабатываем
                    if ($this->settings['breaks'])
                        $text = str_replace("\r\n", "<br/>", $text);
                    // Обрабатываем тэги
                    if ($this->settings['tags']) {
                        $text = bbcode::tags($text);
                    } else {
                        $text = bbcode::notags($text);
                    }
                    // Обрабатываем смайлы
                    if ($this->settings['smileys']) {
                        $text = functions::smileys($text);
                    }
                    // Определяем режим просмотра заголовка - текста
                    $news .= '<div class="news">';
					switch ($this->settings['view']) {
                        case 2 :
                            $news .= '<div class="newsheader"><a href="news/index.php?act=view&amp;id=' . $res['id'] . '">' . htmlentities($res['name'], ENT_QUOTES, 'UTF-8') . '</a> >> <a href="news/index.php?id=' . $res['catid'] . '">' . htmlentities($res['catname'], ENT_QUOTES, 'UTF-8') . '</a> (' . date('d.m.o / H:i', $res['time'] + $sdvigclock * 3600) . ')</div>';
                            break;
                        case 3 :
                            $news .= $text;
                            break;
                        default :
                            $news .= '<div class="newshead"><a href="news/index.php?act=view&amp;id=' . $res['id'] . '">' . htmlentities($res['name'], ENT_QUOTES, 'UTF-8') . '</a> >> <a href="news/index.php?id=' . $res['catid'] . '">' . htmlentities($res['catname'], ENT_QUOTES, 'UTF-8') . '</a> (' . date('d.m.o / H:i', $res['time'] + $sdvigclock * 3600) . ')</div>' . $text;
                    }
                    // Ссылка на каменты
                    if ($this->settings['view'] != 2 && $this->settings['kom'] == 1) {
                        $komm = mysql_result(mysql_query("SELECT COUNT(*) FROM `cms_news_comments` WHERE `refid`='{$res['id']}'"), 0);
                        if ($komm >= 0)
                            $news .= '<br /><a href="news/index.php?act=comments&amp;id=' . $res['id'] . '">' . self::$lng['comments'] . '</a> (' . $komm . ')';
                    }
                    $news .= '</div>';
                    ++$i;
                }
                return $news;
            }
            else {
                return false;
            }
        }
    }

    // Счетчик всех новостей
    private function newscount() {
		$res = mysql_result(mysql_query("SELECT COUNT(*) FROM `cms_news`".(self::$user_rights < 7 ? " WHERE `time`<='" . time() . "'":"").""), 0);
        return ($res > 0 ? $res : '0');
    }

    // Счетчик свежих новостей
    private function lastnewscount() {
        $res = mysql_result(mysql_query("SELECT COUNT(*) FROM `cms_news` WHERE `time` > '" . (time() - (86400 * 3)) . "'".(self::$user_rights < 7 ? " AND `time`<='" . time() . "'":"").""), 0);
        return ($res > 0 ? '/<span class="red">+' . $res . '</span>' : false);
    }
}
